import { Component } from 'vue-property-decorator';
import { FetchService } from '@ibizstudio/api';
import { AppViewBase } from '../../../components';
import { VueLifeCycleProcessing } from '../../../decorators';
import { Util } from '@ibizstudio/runtime';
import './design-model-edit.less';

@Component
@VueLifeCycleProcessing()
export class DesignModelEdit extends AppViewBase {
    /**
     * 是否保存过
     *
     * @type {boolean}
     * @memberof DesignModelEdit
     */
    isSave: boolean = false;

    /**
     * 模型编辑值
     *
     * @type {IPSDEToolbar}
     * @memberof DesignModelEdit
     */
    value: string = '{}';

    /**
     * Vue生命周期，初始化完成
     *
     * @memberof DesignModelEdit
     */
    async viewModelInit(): Promise<any> {
        await super.viewModelInit();
        this.load();
    }

    async load(): Promise<any> {
        const { context } = this;
        const deNamePlural = Util.srfpluralize(context.srfdename).toLowerCase();
        const url: string = `/${deNamePlural}/${
            context[context.srfdename?.toLowerCase()]
        }/exportModel`;
        try {
            const loading = (this as any).$loading({
                lock: true,
                text: '加载中...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            const res = await FetchService.getInstance().post(url, {});
            if (res.status === 200) {
                const data = res.data;
                this.value = JSON.stringify(data);
                this.refCodeEditor()
            }
            loading.close();
            return res;
        } catch (err) {
            this.$throw(err);
        }
    }

    refCodeEditor(int: number = 0) {
        if (int > 10) {
          return;
        }
        const ref : any= this.$refs['code-editor'];
        if (ref) {
          ref.codeEditor.trigger('anyString', 'editor.action.formatDocument');
        } else {
            setTimeout(() => {
                int++;
                this.refCodeEditor(int);
            }, 50);
        }
      }
      
    /**
     * 保存
     *
     * @memberof DesignModelEdit
     */
    async save(close: boolean = false): Promise<any> {
        this.isSave = true;
        const { context } = this;
        const deNamePlural = Util.srfpluralize(context.srfdename).toLowerCase();
        const url: string = `/${deNamePlural}/${
            context[context.srfdename?.toLowerCase()]
        }/importModel`;
        try {
            const loading = (this as any).$loading({
                lock: true,
                text: '保存中...',
                spinner: 'el-icon-loading',
                background: 'rgba(0, 0, 0, 0.7)',
            });
            const res = await FetchService.getInstance().post(url, JSON.parse(this.value));
            if (res.status !== 200) {
                this.$throw(res);
            } else {
                if (close) {
                    this.closeView();
                }
            }
            loading.close();
        } catch (err) {
            this.$throw(err);
        }
    }

    /**
     * 关闭
     *
     * @memberof DesignModelEdit
     */
     closeView() {
        super.closeView(this.isSave ? [{ save: true }] : []);
    }

    render() {
        return (
            <div class='design-model-edit'>
                <div class='view-header'>
                    <div class='toolbar'>
                        <i-button size='small' on-click={() => this.save(true)}>
                            保存并关闭
                        </i-button>
                        <i-button size='small' on-click={() => this.save()}>
                            保存
                        </i-button>
                        <i-button size='small' on-click={() => this.closeView()}>
                            关闭
                        </i-button>
                    </div>
                </div>
                <div class='view-container'>
                    <app-code-editor language='json' v-model={this.value} ref='code-editor'></app-code-editor>
                </div>
            </div>
        );
    }
}
